package com.weike.client;

import io.modelcontextprotocol.client.McpAsyncClient;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
import io.modelcontextprotocol.spec.McpSchema;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.mcp.McpToolUtils;
import org.springframework.ai.model.function.FunctionCallback;
//import org.springframework.ai.openai.OpenAiChatModel;
//import org.springframework.ai.openai.OpenAiChatOptions;
//import org.springframework.ai.openai.api.OpenAiApi;
//import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@SpringBootApplication
public class ClientApplication {

//    @Autowired
//    private McpAsyncClient mcpClient;
//
//    @Autowired
//    private OpenAiChatModel chatModel;

    public static void main(String[] args) {

        SpringApplication.run(ClientApplication.class, args);
    }

/*    @Bean
    public ChatClient chatClient(McpSyncClient mcpClient) {
        // 1. 获取 MCP 工具列表
        McpSchema.ListToolsResult toolsList = mcpClient.listTools();
        System.out.println("可用工具: " + toolsList);

        // 2. 为每个工具创建 FunctionCallback
        List<org.springframework.ai.model.function.FunctionCallingOptions.FunctionCallback> functionCallbacks =
                toolsList.tools().stream().map(tool -> {
                    return org.springframework.ai.model.function.FunctionCallingOptions.FunctionCallbackBuilder()
                            .name(tool.name())  // 工具名称
                            .description(tool.description())  // 工具描述
                            .inputType(Map.class)  // 输入参数类型
                            .function(input -> {  // 执行逻辑
                                McpSchema.CallToolRequest request = new McpSchema.CallToolRequest(tool.name(), input);
                                McpSchema.CallToolResult result = mcpClient.callTool(request);
                                return result.result().toString();  // 返回工具执行结果
                            })
                            .build();
                }).collect(Collectors.toUnmodifiableList());

        // 3. 配置 OpenAiChatOptions
        OpenAiChatOptions options = OpenAiChatOptions.builder()
                .withFunctionCallbacks(functionCallbacks)  // 注册工具回调
                .build();

        // 4. 创建并返回 ChatClient
        return ChatClient.builder(chatModel)
                .defaultOptions(options)
                .build();
    }*/

    @Bean
    public ChatClient functionCallbacks(ChatClient.Builder chatClientBuilder, ToolCallbackProvider tools,
                                                       ConfigurableApplicationContext context) {

        FunctionCallback[] toolCallbacks = tools.getToolCallbacks();
        var chatClient = chatClientBuilder
                .defaultTools(tools)
                .build();


//        System.out.println("\n>>> QUESTION: " + "你好，老八叫什么");
//        System.out.println("\n>>> ASSISTANT: " + chatClient.prompt("你好，老八叫什么").call().content());

        return chatClient;
    }

//        @Bean
//        public McpSyncClient test1(){
//        var stdioParams = ServerParameters.builder("java")
//                .args("-jar", "-Dspring.ai.mcp.server.transport=STDIO" ,  "E:\\ai\\mcpServer\\test\\target\\test-0.0.1-SNAPSHOT.jar")
//                .build();
//
//        var stdioTransport = new StdioClientTransport(stdioParams);
//
//            McpSyncClient client = McpClient.sync(stdioTransport).build();
//
//
//            client.initialize();
//            return client;
//        }

//    public static void test1(){
//        var stdioParams = ServerParameters.builder("java")
//                .args("-jar", "-Dspring.ai.mcp.server.transport=STDIO" ,  "E:\\ai\\mcpServer\\test\\target\\test-0.0.1-SNAPSHOT.jar")
//                .build();
//
//        var stdioTransport = new StdioClientTransport(stdioParams);
//
//        var mcpClient = McpClient.sync(stdioTransport).build();
//
//
//        mcpClient.initialize();
//
//
//        McpSchema.ListToolsResult toolsList = mcpClient.listTools();
//
//        McpSchema.CallToolResult weather = mcpClient.callTool(
//                new McpSchema.CallToolRequest("getWeatherForecastByLocation",
//                        Map.of("latitude", "47.6062", "longitude", "-122.3321")));
//
//        McpSchema.CallToolResult alert = mcpClient.callTool(
//                new McpSchema.CallToolRequest("getAlerts", Map.of("state", "NY")));
//
//        mcpClient.closeGracefully();
//    }
}
